package com.ck.file.service.impl;

import com.ck.common.utils.file.FileUploadUtils;
import com.ck.common.utils.file.UnzipFileUtil;
import com.ck.common.utils.txt.TextUtil;
import com.ck.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author ck
 * @date 2023/8/24 14:59
 */
@Service
@Slf4j
@Primary
public class LocalFileServiceImpl implements FileService {

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.upLoadPath}")
    private String localFilePath;

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;
    @Value("${file.unZipPath}")
    public String unZipPath;
    @Value("${file.directoryPath}")
    public String directoryPath;
    @Autowired
    public ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 本地文件上传
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
            String fileName = FileUploadUtils.upload(localFilePath, file);
            String url=request.getScheme()+"://"+ InetAddress.getLocalHost().getHostAddress()+":"+request.getServerPort()+localFilePrefix+fileName;
            return url;

    }

    /**
     * 文件解压接口
     * @return
     */
    @Override
    public String extractTarGz() throws IOException {
        List<File> allTarGzFile = UnzipFileUtil.getAllTarGzFile(unZipPath);
        log.info("获取压缩包文件数:{}",allTarGzFile.size());
        // 使用 CountDownLatch 确保所有任务完成后再返回结果
        CountDownLatch latch = new CountDownLatch(allTarGzFile.size());

        for (File file : allTarGzFile) {
                threadPoolTaskExecutor.execute(() -> {
                    try {
                        log.info("线程 {} 开始解压文件: {}", Thread.currentThread().getName(), file.getName());
                        UnzipFileUtil.processFile(file, directoryPath);
                    } catch (IOException e) {
                      log.error("解压文件失败:{}", TextUtil.ex2Txt(e));
                    }
                    finally {
                        latch.countDown();
                    }
                });
        }
        try {
            // 等待所有任务完成
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("线程被中断:{}", TextUtil.ex2Txt(e));
        }
        return "解压成功";
    }
}
